/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.service;

import br.com.foxline.enums.Status;
import br.com.foxline.model.Enterprise;
import br.com.foxline.model.Lot;
import br.com.foxline.util.Msg;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author ely
 */
@Stateless
public class EnterpriseService extends GenericService<Enterprise> {

    public EnterpriseService() {
        super(Enterprise.class);
    }

    @Override
    public void save(Enterprise entity) {
        try {
            entity.setCreate_at(new Date());
            super.save(entity);
            Msg.messagemInfo("Operação realizada com Sucesso");
        } catch (Exception e) {
            Msg.messagemError("Erro na Operação");
            e.printStackTrace();
        }
    }

    public List<Enterprise> autocomplete(String name) {
        List<Enterprise> lista = new ArrayList<Enterprise>();
        String sql = "Select e from Enterprise e where lower(e.name) like lower(:name)";
        Query query = getEntityManager().createQuery(sql).setMaxResults(50);

        if (name != null) {
            query.setParameter("name", "" + name + "%");
        }

        lista = query.getResultList();
        return lista;
    }
    
    public List<Lot> findEnterprise(Enterprise enterprise, Lot lot, Integer block, Status status){
    
        String sql = "Select l from Lot l JOIN l.enterprise e where"
                + " e.id = :id and ";
        if(status != null)
                sql += " l.status = :status and ";
        if(lot != null && lot.getId() != null)
                sql += " l.id = :idLot and";
        if(block != null)
                sql += " l.block like :block and ";
        sql += " 1=1 order by l.num, l.block ASC";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("id", enterprise.getId());
        if(lot != null && lot.getId() != null)
        query.setParameter("idLot", lot.getId());
        if(block != null)
            query.setParameter("block", ""+block);
        if(status != null)
            query.setParameter("status", status);    
        
        return query.getResultList();
    }
}

